package com.xuelang.pipeline.entry.application;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xuelang.pipeline.app.application.ApplicationService;
import com.xuelang.pipeline.app.application.ComponentService;
import com.xuelang.pipeline.app.pipeline.PipelineInstanceService;
import com.xuelang.pipeline.app.task.TaskInstanceService;
import com.xuelang.pipeline.client.application.IApplicationService;
import com.xuelang.pipeline.client.application.IApplicationsService;
import com.xuelang.pipeline.client.application.dto.ApplicationComponentDTO;
import com.xuelang.pipeline.client.application.dto.ApplicationDTO;
import com.xuelang.pipeline.client.application.dto.ApplicationQuery;
import com.xuelang.pipeline.client.application.dto.ComponentDTO;
import com.xuelang.pipeline.client.common.request.PageParam;
import com.xuelang.pipeline.client.common.result.ApiResult;
import com.xuelang.pipeline.client.common.result.PageRecord;
import com.xuelang.pipeline.client.pipeline.dto.PipelineInstanceDTO;
import com.xuelang.pipeline.client.task.dto.TaskInstanceDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 上航项目API
 *
 * @author liuyuan.ly
 * @since 2024/5/14 9:54
 */
@Slf4j
@RestController
@RequestMapping("/applcations")
public class ApplicationsController implements IApplicationsService {

    @Autowired
    private ApplicationService applicationService;
    @Autowired
    private ComponentService componentService;
    @Autowired
    private TaskInstanceService taskInstanceService;
    @Autowired
    private PipelineInstanceService pipelineInstanceService;

    @Override
    public ApiResult<List<Map<String, Object>>> queryApplicationsByUserId(String userid) {

        List<ApplicationComponentDTO> applicationComponentDTOS = applicationService
                .listWithComponent(
                        ApplicationQuery
                                .builder()
                                .userId(userid)
                                .build()
                );

        List<Map<String, Object>> list = Lists.newArrayList();
        applicationComponentDTOS.forEach(applicationComponentDTO -> {
            Map<String, Object> application = Maps.newHashMap();
            application.put("objectType", "appGroup");
            application.put("objectName", applicationComponentDTO.getName());
            application.put("objectCode", applicationComponentDTO.getCode());

            List<Map<String, Object>> componentList = Lists.newArrayList();
            application.put("applicationList", componentList);
            applicationComponentDTO.getComponents().forEach(componentDTO -> {
                Map<String, Object> component = Maps.newHashMap();
                component.put("objectType", "application");
                component.put("applicationId", componentDTO.getId());
                component.put("applicationCode", componentDTO.getCode());
                component.put("applicationName", componentDTO.getName());
                component.put("applicationType", componentDTO.getComponentType() == 1 ? "webservice" : "backservice");
                component.put("imageTag", componentService.queryComponentImageTagList(componentDTO.getId()));
                try {
                    List<String> imageTagList = Lists.newArrayList();
                    List<PipelineInstanceDTO> pipelineInstanceDTOS = pipelineInstanceService.listByComponentLabel(componentDTO.getLabel());
                    log.info(">>>获取分支、镜像tag.pipelineInstanceDTOS>>>{}", JSON.toJSONString(pipelineInstanceDTOS));
                    if (CollUtil.isNotEmpty(pipelineInstanceDTOS)) {
                        PipelineInstanceDTO latestPipelineInstance = pipelineInstanceDTOS.get(0);
                        List<TaskInstanceDTO> taskInstanceList = taskInstanceService.queryByPipelineInstanceId(latestPipelineInstance.getInstanceCode());
                        log.info(">>>获取分支、镜像tag.taskInstanceList>>>{}", JSON.toJSONString(taskInstanceList));
                        if (CollUtil.isNotEmpty(taskInstanceList)) {
                            taskInstanceList.forEach(taskInstanceDTO -> {
                                String truncateTaskInstanceCode = taskInstanceDTO.getCode().replaceFirst(taskInstanceDTO.getPipelineInstanceCode(), "");
                                if (truncateTaskInstanceCode.contains("kaniko")) {
                                    String output = taskInstanceDTO.getOutput();
                                    Optional.ofNullable(output).ifPresent(data -> {
                                        imageTagList.add(output);
                                    });
                                }
                            });
                        }
                    }
                    component.put("imageTag", imageTagList);
                } catch (Exception e) {
                    log.error(">>>获取分支、镜像tag出错>>>{}", e.getMessage());
                }
                componentList.add(component);
            });
            list.add(application);
        });

        return ApiResult.success(list);
    }


    @Override
    public ApiResult<Map<String, Object>> queryComponentByidV2(String componentId) {
        ComponentDTO componentDTO = componentService.queryById(Long.parseLong(componentId));

        Map<String, Object> result = Maps.newHashMap();
        if (componentDTO != null) {

            result.put("applicationId", componentId);
            result.put("applicationCode", componentDTO.getCode());
            result.put("applicationName", componentDTO.getName());
            result.put("applicationType", componentDTO.getComponentType() == 1 ? "webservice" : "backservice");
            result.put("description", componentDTO.getLabel());
            result.put("gitUrl", componentDTO.getCodeRepository());
            result.put("imageRegistryType", Lists.newArrayList("Aliyun"));
            result.put("branch", Lists.newArrayList("main"));
//            result.put("imageUrl", "https://aliyun.com/shanghangProject/imageName-applicationCode");
            // 镜像tag
            result.put("imageTag", componentService.queryComponentImageTagList(Long.parseLong(componentId)));

            try {
                List<PipelineInstanceDTO> pipelineInstanceDTOS = pipelineInstanceService.listByComponentLabel(componentDTO.getLabel());
                log.info(">>>获取分支、镜像tag.pipelineInstanceDTOS>>>{}", JSON.toJSONString(pipelineInstanceDTOS));
                if (CollUtil.isNotEmpty(pipelineInstanceDTOS)) {
                    PipelineInstanceDTO latestPipelineInstance = pipelineInstanceDTOS.get(0);
                    List<TaskInstanceDTO> taskInstanceList = taskInstanceService.queryByPipelineInstanceId(latestPipelineInstance.getInstanceCode());
                    log.info(">>>获取分支、镜像tag.taskInstanceList>>>{}", JSON.toJSONString(taskInstanceList));
                    if (CollUtil.isNotEmpty(taskInstanceList)) {
                        taskInstanceList.forEach(taskInstanceDTO -> {
                            String truncateTaskInstanceCode = taskInstanceDTO.getCode().replaceFirst(taskInstanceDTO.getPipelineInstanceCode(), "");
                            if (truncateTaskInstanceCode.contains("git-clone")) {
                                String params = taskInstanceDTO.getParams();
                                Optional.ofNullable(params).ifPresent(data -> {
                                    JSONObject paramsData = JSON.parseObject(data);
                                    if (paramsData != null) {
                                        String branch = paramsData.getString("branch");
                                        result.put("branch", Lists.newArrayList(
                                                "{{componentCodeBranch}}".equals(branch) ? "master" : branch
                                        ));
                                    }
                                });
                            }
                            if (truncateTaskInstanceCode.contains("kaniko")) {
                                String output = taskInstanceDTO.getOutput();
                                Optional.ofNullable(output).ifPresent(data -> {
                                    result.put("imageTag", output);
                                });
                            }
                        });
                    }
                }
            } catch (Exception e) {
                log.error(">>>获取分支、镜像tag出错>>>{}", e.getMessage());
            }

        }
        return ApiResult.success(result);
    }

    @Override
    public ApiResult<Map<String, Object>> queryComponentByid(String componentId) {
        ComponentDTO componentDTO = componentService.queryById(Long.parseLong(componentId));

        Map<String, Object> result = Maps.newHashMap();

        if (componentDTO != null) {
            result.put("applicationId", componentId);
            result.put("applicationCode", componentDTO.getCode());
            result.put("applicationName", componentDTO.getName());
            result.put("applicationType", componentDTO.getComponentType() == 1 ? "webservice" : "backservice");
            result.put("description", componentDTO.getLabel());
            result.put("gitUrl", componentDTO.getCodeRepository());
            result.put("branch", Lists.newArrayList("main"));
            result.put("imageRegistryType", Lists.newArrayList("Aliyun"));
//            result.put("imageUrl", "https://aliyun.com/shanghangProject/imageName-applicationCode");
            // 镜像tag
            result.put("imageTag", componentService.queryComponentImageTagList(Long.parseLong(componentId)));
        }
        return ApiResult.success(result);
    }


    @Override
    public ApiResult<List<String>> queryComponentImageTagList(String componentId) {
        return ApiResult.success(componentService.queryComponentImageTagList(Long.parseLong(componentId)));
    }
}
